package com.wing.portal.aggregation.portletinfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.wing.cms.domain.Portlet1;
import com.wing.cms.service.ChannelManager;
import com.wing.cms.service.Portlet1Manager;
import com.wing.common.util.SpringDI;

@Service
public class MenuPortletInfo implements PortletInfo {

	public Map loadPortletInfo(Map<String, String> param) {
		Map root = new HashMap();
		String portletId = param.get("portletid");
		String siteId = param.get("siteId");
		Portlet1Manager portletInstanceManager = (Portlet1Manager) SpringDI
				.getBean("portlet1Manager");

		Portlet1 portletInfo = portletInstanceManager.findById(portletId);
		if(portletInfo==null){
			root.put("portletWidth", 40);
			root.put("portletheight", 10);
			return root;
		}
		int portletWidth = portletInfo.getPortletwidth();
		int portletheight = portletInfo.getPortletheight();
		root.put("title", portletInfo.getTitle());
		root.put("titlecolor", portletInfo.getTitlecolor());
		root.put("titletype", portletInfo.getTitletype()==null?"0":portletInfo.getTitletype());
		root.put("titlepic", portletInfo.getTitlepic());
		root.put("isopened", portletInfo.getIsopened());
		root.put("showlevel", portletInfo.getShowlevel());
		root.put("portletWidth", portletWidth);
		root.put("portletheight", portletheight);
		root.put("menu",
				findChannelsByChIdStart(portletInfo.getMenuchannelid(),siteId).get("childList"));
		return root;
	}

	private Map<String, Object> findChannelsByChIdStart(String chId ,String siteId) {
		ChannelManager channelManager = (ChannelManager) SpringDI.getBean("channelManager");
		Map<String, Object> rootChannel =new HashMap<String, Object>();
		rootChannel.put("id", chId);
		findChannelsByChId(rootChannel,channelManager, chId,siteId);
		return rootChannel;
	}

	private void findChannelsByChId(Map<String, Object> parentChannel,ChannelManager channelManager, String chId,String siteId) {
		List<Map<String, Object>> channels = channelManager.findChildsByPid(chId,siteId);
		for (Map<String, Object> channel : channels) {
			findChannelsByChId(channel,channelManager,(String) channel.get("id"),siteId);
		}
		parentChannel.put("childList", channels);
	}

	/**
	 * 通过portletId查找模板位置
	 * 
	 * @param portletId
	 * @return templateFilePath
	 */

	public String findTemplateFile(String portletId) {
		Portlet1Manager portletInstance1Manager = (Portlet1Manager) SpringDI
				.getBean("portlet1Manager");
		return portletInstance1Manager.findTemplateFile(portletId);
	}

}
